package com.springboot.mybatis.service.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author sunyt31481
 * @date 2020/8/12 9:31
 * @description
 */
public class RabbitMqUtil {
    /**
     * 使用静态变量赋值，在类加载过程中只需加载一次，避免调用方法时重复创建对象
     */
    private static ConnectionFactory connectionFactory;
    static{
        connectionFactory  = new ConnectionFactory();
        connectionFactory.setHost("LocalHost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/ems");
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("1");
    }
    /**
     * @描述 创建连接对象的方法
     */
    public static Connection getConnect() throws IOException, TimeoutException {
        try {
            /*ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("LocalHost");
            connectionFactory.setPort(5672);
            connectionFactory.setVirtualHost("/ems");
            connectionFactory.setUsername("ems");
            connectionFactory.setPassword("1");*/
            return connectionFactory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @描述 创建关闭连接的方法
     */
    public static void closeConnect(Channel channel, Connection connection){
        try {
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
